import { GLOBAL_CONFIG } from '@/const/storage'
import { DARK_THEME, PRIMARY_COLOR } from '@/const/theme'
import { isString, isNumber, isStringNumber } from '@/utils/type'
import { isHexColor } from '@/utils/regexp'
import { getStorage, setStorage } from './storage'

// hex颜色转rgb颜色
function hexToRgb(str: string): number[] {
  str = str.replace('#', '')
  const hxs = str.match(/../g) || []
  return hxs.slice(0, 3).map((hex) => parseInt(hex, 16))
}

// rgb颜色转hex颜色
function rgbToHex(r: number, g: number, b: number): string {
  const hex = [r, g, b].map((num) => {
    const hexStr = num.toString(16)
    return hexStr.length === 1 ? '0' + hexStr : hexStr
  })
  return '#' + hex.join('')
}

// 变淡
export function lighten(color: string, level: number): string {
  const rgba: number[] = hexToRgb(color)
  if (rgba.length < 3) {
    throw new Error('Invalid color format')
  }
  for (let i = 0; i < 3; i++) rgba[i] = Math.floor((255 - rgba[i]!) * level + rgba[i]!)
  return rgbToHex(rgba[0]!, rgba[1]!, rgba[2]!)
}

// 加深
export function darken(color: string, level: number): string {
  const rgba: number[] = hexToRgb(color)
  if (rgba.length < 3) {
    throw new Error('Invalid color format')
  }
  for (let i = 0; i < 3; i++) rgba[i] = Math.floor(rgba[i]! * (1 - level))
  return rgbToHex(rgba[0]!, rgba[1]!, rgba[2]!)
}

// 添加暗黑样式
export function addThemeClass(mode: string) {
  if (!isString(mode)) throw new Error(`必须传入一个字符串类型的参数，而不是${typeof mode}`)

  setStorage(GLOBAL_CONFIG, { ...getStorage(GLOBAL_CONFIG), theme: mode })
  // EXPLAIN: 没必要再去调用useConfigStore
  document.documentElement.classList[mode === DARK_THEME ? 'add' : 'remove'](DARK_THEME)
}

// 切换主题色
export function changePrimaryColor(color: string) {
  if (!isHexColor(color)) throw new Error('你必须传入一个16进制的color值')

  const namespace = '--app-color-primary'
  document.documentElement.style.setProperty(namespace, color)
  for (let i = 1; i <= 9; i++) {
    document.documentElement.style.setProperty(`${namespace}-light-${i}`, lighten(color, i / 10))
  }
  for (let i = 1; i <= 9; i++) {
    document.documentElement.style.setProperty(`${namespace}-darken-${i}`, darken(color, i / 10))
  }
}

// 获取单个css变量值
export function getCssProperty(namespace: string): string {
  return getComputedStyle(document.documentElement).getPropertyValue(namespace)
}

// 设置单个css变量值
export function setCssProperty(namespace: string, value: string): void {
  document.documentElement.style.setProperty(namespace, value)
}

/**
 * @description 添加单位
 * @param {string | number} value
 * @param {string} unit
 * @return {string | number}
 */
export function addUnit(value: string | number, unit = 'px'): string {
  if (!value) return ''
  if (isNumber(value as number) || isStringNumber(value as string)) {
    return `${value}${unit}`
  } else if (isString(value)) {
    return value as string
  }
  return ''
}

// 获取全局CSS变量（只获取--app-开头的）
export function getAppCssVariables() {
  const vars: Record<string, string> = {}
  const isStyleRule = (rule: CSSRule): rule is CSSStyleRule => rule.type === CSSRule.STYLE_RULE

  for (const sheet of Array.from(document.styleSheets)) {
    let rules: CSSRuleList | undefined
    try {
      rules = sheet.cssRules
    } catch {
      continue
    }
    if (!rules) continue

    for (const rule of Array.from(rules)) {
      if (isStyleRule(rule) && rule.selectorText === ':root') {
        for (let i = 0; i < rule.style.length; i++) {
          const name = rule.style[i]!
          if (name.startsWith('--app-')) {
            vars[name] = rule.style.getPropertyValue(name).trim()
          }
        }
      }
    }
  }

  return { ...vars, '--app-primary-color': PRIMARY_COLOR }
}

/**
 * 根据传入的颜色值计算禁用的颜色
 * @param {string} hexColor - 十六进制颜色值，例如 "#3498db"
 * @param {number} [factor=0.5] - 调整颜色的因子，默认为0.7
 * @return {string} - 计算后的禁用颜色值
 */
export function getDisabledColor(hexColor: string, factor = 0.5, alpha = 0.8): string {
  // 确保颜色值以 "#" 开头
  if (hexColor.startsWith('#')) {
    hexColor = hexColor.slice(1)
  }

  // 将颜色值分解为 RGB
  let r = parseInt(hexColor.substring(0, 2), 16)
  let g = parseInt(hexColor.substring(2, 4), 16)
  let b = parseInt(hexColor.substring(4, 6), 16)

  // 计算禁用颜色
  r = Math.min(255, Math.floor(r + (255 - r) * factor))
  g = Math.min(255, Math.floor(g + (255 - g) * factor))
  b = Math.min(255, Math.floor(b + (255 - b) * factor))

  return `rgba(${r}, ${g}, ${b}, ${alpha})`
}

export function hexToRgba(hex: string, alpha = 1): string {
  // 去掉可能的前缀#
  hex = hex.replace(/^#/, '')

  // 解析颜色值
  let r, g, b
  if (hex.length === 3) {
    r = parseInt(hex[0]! + hex[0]!, 16)
    g = parseInt(hex[1]! + hex[1]!, 16)
    b = parseInt(hex[2]! + hex[2]!, 16)
  } else if (hex.length === 6) {
    r = parseInt(hex.slice(0, 2), 16)
    g = parseInt(hex.slice(2, 4), 16)
    b = parseInt(hex.slice(4, 6), 16)
  } else {
    throw new Error('Invalid hex color format')
  }

  // 返回rgba格式
  return `rgba(${r}, ${g}, ${b}, ${alpha})`
}

export function changeAsideStyle(isDarkAside: boolean) {
  document.documentElement.classList[isDarkAside ? 'add' : 'remove']('dark-aside')
}
